let screenStream;
let audioStream;
let recorder;
let audioContext;

// 与弹窗交互页面通信
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  switch (request.action) {
    case "startRecording":
      startRecording();
      break;
    case "stopRecording":
      stopRecording();
      break;
    case "screenShot":
      screenShot();
      break;
    default:
      return;
  }
  sendResponse({ success: true });
});

// 开始录制
async function startRecording() {
  try {
    // 获取屏幕媒体流
    screenStream = await navigator.mediaDevices.getDisplayMedia();
    if (!screenStream) return;

    // 获取系统音频媒体流
    audioStream = await navigator.mediaDevices
      .getUserMedia({ audio: true })
      .catch(() => false);

    let stream = screenStream;

    // 获取到麦克风流
    if (audioStream) {
      audioContext = new (window.AudioContext || window.webkitAudioContext)();
      // filterBand(audioStream);

      // 合并屏幕和音频媒体流
      stream = new MediaStream([
        ...screenStream.getTracks(),
        ...audioStream.getTracks(),
      ]);
    }

    recorder = new MediaRecorder(stream);
    // 存储录制状态
    chrome.storage.local.set({ recording: true });

    // 录制开始
    recorder.start();
    recorder.addEventListener("dataavailable", handleDataAvailable);

    // 监听视频流的停止事件
    screenStream.getVideoTracks()[0].addEventListener("ended", () => {
      stopRecording();
    });
  } catch (error) {
    console.log("Failed to start recording:", error.message);
    if (error.message == "Permission denied") return;
    // 断开设备的采集
    if (audioStream) {
      audioStream.getTracks().forEach((track) => track.stop());
    }
    if (screenStream) {
      screenStream.getTracks().forEach((track) => track.stop());
    }
    // 提示用户错误信息
    alert("开始录制失败,请检查设备");
  }
}

// 停止录制
function stopRecording() {
  if (!recorder || recorder.state != "recording") return;
  // 录制结束
  recorder.stop();

  // 停止屏幕和音频流
  screenStream.getTracks().forEach((track) => track.stop());
  audioStream && audioStream.getTracks().forEach((track) => track.stop());

  // 存储录制状态
  chrome.storage.local.set({ recording: false });
}

// 降噪
function noiseReduction(stream) {
  // 创建音频输入节点
  const input = audioContext.createMediaStreamSource(stream);

  // 创建BiquadFilterNode，用于进行滤波
  const filter = audioContext.createBiquadFilter();
  filter.type = "lowpass"; // 使用低通滤波器类型
  filter.frequency.value = 100; // 设置截止频率Hz

  // 连接节点
  input.connect(filter);
  filter.connect(audioContext.destination);
}

// 滤波
function filterBand(stream) {
  // 动态压缩器
  compressor = audioContext.createDynamicsCompressor();
  compressor.threshold.value = -50; // 压缩的起始阈值，以分贝（dB）为单位。超过该阈值的信号将被压缩。
  compressor.knee.value = 40; // 指定压缩器在压缩开始之前达到压缩曲线的斜率。这个值越小，曲线越陡峭。
  compressor.ratio.value = 12; // 压缩比，指定压缩器的压缩率。例如，如果设置为4，则表示每增加1dB的输入，输出只增加0.25dB。
  compressor.reduction.value = -20; // 当前压缩器的压缩量，以分贝（dB）为单位。
  compressor.attack.value = 0; // 压缩器的响应时间，即从超过阈值到开始压缩的时间，以秒为单位。
  compressor.release.value = 0.25; //释放时间，即从低于阈值到停止压缩的时间，以秒为单位。

  // 双二阶滤波器
  filter = audioContext.createBiquadFilter();
  filter.Q.value = 8.3; // 品质因数，指定滤波器的带宽。
  filter.frequency.value = 355; // 滤波器的中心频率。
  filter.gain.value = 3.0; // 滤波器的增益。
  filter.type = "bandpass"; // 滤波器的类型,带通:允许两个频率截止范围内的信号。
  filter.connect(compressor);

  compressor.connect(audioContext.destination);
  filter.connect(audioContext.destination);

  const mediaStreamSource = audioContext.createMediaStreamSource(stream);
  mediaStreamSource.connect(filter);
}
// 屏幕截图
async function screenShot() {
  try {
    // 创建画布和绘图上下文
    const canvas = document.createElement("canvas");
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
    const context = canvas.getContext("2d");

    // 创建视频元素播放屏幕流
    const video = document.createElement("video");
    video.setAttribute("autoplay", "autoplay");

    // 获取屏幕流并设置给视频元素
    const captureStream = await navigator.mediaDevices.getDisplayMedia();
    video.srcObject = captureStream;

    // 等待视频元数据加载完成
    // await new Promise((resolve) => (video.onloadedmetadata = resolve));
    setTimeout(() => {
      // 将视频绘制到画布上
      context.drawImage(video, 0, 0);
      // 获取画布内容并发送给后台处理
      handlePic(canvas.toDataURL("image/png"));
      // 停止屏幕流并清理资源
      captureStream.getTracks().forEach((track) => track.stop());
      canvas.remove();
      video.remove();
    }, 200);
  } catch (error) {
    console.log("Failed to start recording:", error.message);
    if (error.message == "Permission denied") return;
    alert("截图失败，检查分享设置");
  }
}

// 处理录制数据
function handleDataAvailable(event) {
  const url = URL.createObjectURL(event.data);
  chrome.runtime.sendMessage({ action: "download", url }, () => {
    URL.revokeObjectURL(url);
  });
}

// 处理图片
function handlePic(url) {
  chrome.runtime.sendMessage({ action: "download", url, type: "png" });
}
